(function($){
	var KEY = "jforest.fileManager";
	
	var FileManager = function(element,options){
		this.$el = $(element);
		this.options = $.extend({
			type:'image',
			token:'token',
			multiple:false,
			resDomain:'',
			addImgPath:'',
			imgs:{
				mp3:'/assets/extends/ui/imgs/mp3.png',
				mp4:'/assets/extends/ui/imgs/mp4.png'
			}
		},options);
		
		this.currPath = this.$el.hide().val();
		this._createUi();
	};

	FileManager.prototype = {
		_createUi:function(){
			var self = this;
			this.packDiv = this.$el.wrap('<div class="jf-file-manage clearfix"></div>').parent();
			if(this.options.multiple){
				this.packDiv.append('<div class="images"></div>');
				if(this.currPath){
					let arr = this.currPath.split('|');
					for(var i=0;i<arr.length;i++){
						this._buildMultipleImg(arr[i]);
					}
				}
				var addImgPath = this.options.addImgPath;
				$('<div class="img-thumbnail">'
					+'<img src="'+addImgPath+'" class="img-responsive" style="width:100%;"/></div>').appendTo(this.packDiv).click(function(){
					self.select();
				});
			}else{
				if(this.currPath){
					let imgPath = this.options.resDomain + this.currPath;
					let html = '<div class="img-thumbnail pull-left" data-path="'+this.currPath+'">'
						+'<img src="'+imgPath+'" class="img-responsive" style="width:100%;"/>'
						+'<div class="btn-panel"><button type="button" class="close"><span>&times;</span></button></div></div>';
					$(html).appendTo(this.packDiv).click(function(){
						self.select();
					}).find('.close').click(function(){
						self.close(this);
					});
				}else{
					var addImgPath = this.options.addImgPath;
					var html = '<div class="img-thumbnail">'
							+'<img src="'+addImgPath+'" class="img-responsive" style="width:100%;"/></div>';
					$(html).appendTo(this.packDiv).click(function(){
						self.select();
					});
				}
			}
		},
		_buildMultipleImg:function(path){
			var self = this;
			let imgPath = this.options.resDomain + path;
			var html = '<div class="img-thumbnail pull-left" data-path="'+path+'">'
				+'<img src="'+imgPath+'" class="img-responsive" style="width:100%;"/>'
				+'<div class="btn-panel">'
					+'<a href="javascript:void(0);" class="pull-left"><i class="fa fa-arrow-left"/></a>'
					+'<a href="javascript:void(0);" class="pull-left"><i class="fa fa-arrow-right"/></a>'
					+'<button type="button" class="close"><span>&times;</span></button></div>'
				+'</div>';
			html = $(html).appendTo(self.packDiv.find('.images'));
			html.find('.close').click(function(){
				self.close(this);
			});
			html.find('.fa-arrow-left').parent().click(function(){
				if(html.prev()){
					html.after(html.prev());
					let paths = '';
					self.packDiv.find('.images .img-thumbnail').each(function(i,e){
						var path = $(e).data('path');
						if(path){
							paths = paths + '|' +path;
						}
					});
					if(paths.indexOf('|')==0){
						self.$el.val(paths.substr(1));
					}else{
						self.$el.val(paths);
					}
				}
			});
			html.find('.fa-arrow-right').parent().click(function(){
				if(html.next()){
					html.before(html.next());
					let paths = '';
					self.packDiv.find('.images .img-thumbnail').each(function(i,e){
						var path = $(e).data('path');
						if(path){
							paths = paths + '|' +path;
						}
					});
					if(paths.indexOf('|')==0){
						self.$el.val(paths.substr(1));
					}else{
						self.$el.val(paths);
					}
				}
			});
			return html;
		},
		set:function(path){
			var self = this;
			if(path && path != ''){
				if(self.options.multiple){
					var paths = self.$el.val();
					paths = paths + '|' +path;
					if(paths.indexOf('|')==0){
						self.$el.val(paths.substr(1));
					}else{
						self.$el.val(paths);
					}
					self._buildMultipleImg(path);
				}else{
					var imgPath = self.options.resDomain + path;
					self.$el.val(path);
					self.packDiv.find('.img-thumbnail img').attr('src',imgPath);
					if(self.packDiv.find('.img-thumbnail .close').length == 0){
						var html = '<div class="btn-panel"><button type="button" class="close"><span>&times;</span></button></div>';
						$(html).appendTo(self.packDiv.find('.img-thumbnail')).find('.close').click(function(){
							self.close(this);
						});
					}
				}
			}else if(!self.options.multiple){
				self.clear();
			}
		},
		clear:function(){
			var self = this;
			self.$el.val('');
			if(self.options.multiple){
				self.packDiv.find('.images').empty();
			}else{
				self.packDiv.find('.img-thumbnail img').attr('src',self.options.addImgPath);
				self.packDiv.find('.img-thumbnail .btn-panel').remove();
			}
		},
		select:function(){
			var key = new Date().getTime();
			var self = this;
			$.jBox('iframe:'+this.options.resDomain+'/file/manage.html?type='+self.options.type+'&token='+self.options.token+'&key='+key, {
			    title: "图片管理器",
			    width:800,
			    height:400,
			    buttons:{'确定':1,'关闭':0},
			    submit:function(v, h, f){
			    	if(v == 1){
			    		$.ajax({
			                async : false,
			                url : self.options.resDomain+'/file/select/get.do',
			                type : "GET",
			                dataType : "jsonp", // 返回的数据类型，设置为JSONP方式
			                jsonp : 'jsoncallback', //指定一个查询参数名称来覆盖默认的 jsonp 回调参数名 callback
			                jsonpCallback: '_get', //设置回调函数名
			                data : {key:key}, 
			                success: function(result, status, xhr){
			                	if(result.error == 0){
			                		self.set(result.data.filePath);
				    			}else{
				    				jf.error(result.msg);
				    			}
			                }
			            });
			    	}
			    }
			});
		},
		close:function(el){
			var paths = '';
			if(this.options.multiple){
				$(el).parents('.img-thumbnail').remove();
				this.packDiv.find('.images .img-thumbnail').each(function(i,e){
					var path = $(e).data('path');
					if(path){
						paths = paths + '|' +path;
					}
				});
			}else{
				var addImgPath = this.options.addImgPath;
				$(el).parents('.img-thumbnail').find('img').attr('src',addImgPath);
				$(el).parent().remove();
			}
			if(paths.indexOf('|')==0){
				this.$el.val(paths.substr(1));
			}else{
				this.$el.val(paths);
			}
			event.stopPropagation();
		}
	};
	
	$.fn.jfFileManager = function(){
		var args = Array.prototype.slice.call(arguments, 0);
		var value = undefined;
		this.each(function () {
			var $this = $(this);
			if (args.length === 0 || typeof(args[0]) === "object") {
				opts = args.length === 0 ? {} : $.extend({}, args[0]);
				value = new FileManager(this,opts);//创建控件
				$this.data(KEY,value); 
			}else if (typeof(args[0]) === "string"){
				var entity = $this.data(KEY);
                if(entity === undefined){return;}
                value = entity[args[0]].apply(entity, args.slice(1));
			}else{
				 throw 'Invalid arguments to '+KEY+' plugin: ' + args;
			}
	    });
	    return (value === undefined) ? this : value;
	};
	
	$.fn.jfFileManager.Constructor = FileManager;
	
})(window.jQuery)